import * as React from 'react';
import { useLocation, history } from 'umi';
import { Menu } from 'antd';

import menuList from './menulist.js';

const { SubMenu } = Menu;

export default () => {
  const location = useLocation();
  const [selectedKeys, setSelectedKeys] = React.useState([]);
  const [openKeys, setOpenKeys] = React.useState([]);
  React.useEffect(() => {
    setSelectedKeys([location.pathname]);
    for (let item of menuList) {
      if (item.key === location.pathname) {
        setOpenKeys([location.pathname]);
        break;
      } else if (item.subList) {
        if (item.subList.find(subs => subs.key === location.pathname)) {
          setOpenKeys([item.key]);
          break;
        }
      }
    }
    return () => {};
  }, [location]);
  return (
    <Menu
      theme="dark"
      openKeys={openKeys}
      onOpenChange={keys => setOpenKeys(keys)}
      selectedKeys={selectedKeys}
      onClick={({ key }) => {
        setSelectedKeys([key]);
        history.push(key);
      }}
      mode="inline"
    >
      {menuList.map(item => {
        if (item.hide) {
          return null;
        }
        if (item.subList && Array.isArray(item.subList)) {
          return (
            <SubMenu key={item.key} icon={item.icon} title={item.title}>
              {item.subList.map(subItem =>
                subItem.hide ? null : (
                  <Menu.Item key={subItem.key} icon={subItem.icon}>
                    {subItem.title}
                  </Menu.Item>
                ),
              )}
            </SubMenu>
          );
        }
        return (
          <Menu.Item key={item.key} icon={item.icon}>
            {item.title}
          </Menu.Item>
        );
      })}
    </Menu>
  );
};
